import { defineEventHandler } from 'h3'
import redis from '../../util/redis'
import { checkAdminKey } from './_utils'
import { recordLog } from '../../util/log'

export default defineEventHandler(async (event: any) => {
  const ck = await checkAdminKey(event)
  if (!ck.ok) return { status: event.node.res.statusCode || 401, message: ck.message }

  try {
    const fullKeys: string[] = await (redis as any).keys('ym:*')
    const list = [] as any[]
    for (const fk of (fullKeys || [])) {
      try {
        const ttl = await (redis as any).ttl(fk)
        list.push({ key: fk.replace(/^ym:/, ''), ttl })
      } catch (e) {
        list.push({ key: fk.replace(/^ym:/, ''), ttl: -2 })
      }
    }
    await recordLog(event as any, { message: `admin/ym: list keys count=${list.length}`, userId: 0 })
    return { status: 'ok', keys: list }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `admin/ym: redis keys failed ${String(err)}`, userId: 0 })
    return { status: 500, message: 'redis keys failed', error: String(err) }
  }
})
